<?php
/**
* @file Compat.php
* PHP4 compatibility Subroutines for Portamx.
*
* @author PortaMx - Portal Management Extension
* @author Copyright 2008-2011 by PortaMx - http://portamx.com
* @Version: 1.0 RC4
* @Date: 23.02.2011
*/

if(!defined('PortaMx'))
	die('This file can\'t be run without PortaMx');

/**
* parse_url values
*/
if(@version_compare(PHP_VERSION, '5.1.2') < 0)
{
	define('PHP_URL_SCHEME', 'scheme');
	define('PHP_URL_HOST', 'host');
	define('PHP_URL_PORT', 'port');
	define('PHP_URL_USER', 'user');
	define('PHP_URL_PASS', 'pass');
	define('PHP_URL_PATH', 'path');
	define('PHP_URL_QUERY', 'query');
	define('PHP_URL_FRAGMENT', 'fragment');
}

/**
* get domain and path for cookies
*/
function pmx_getcookparts()
{
	global $boardurl, $modSettings;

	$url = pmx_parse_url($boardurl);

	// local cookie?
	if(empty($url['path']) || empty($modSettings['localCookies']))
		$url['path'] = '';
	$url['path'] .= '/';

	// global cookie?
	if(!empty($modSettings['globalCookies']) && preg_match('~^\d{1,3}(\.\d{1,3}){3}$~', $url['host']) == 0 && preg_match('~(?:[^\.]+\.)?([^\.]{2,}\..+)\z~i', $url['host'], $parts) == 1)
		$url['host'] = '.'. $parts[1];
	elseif(empty($modSettings['localCookies']) && empty($modSettings['globalCookies']))
		$url['host'] = '';
	elseif(!isset($url['host']) || strpos($url['host'], '.') === false)
		$url['host'] = '';

	return $url;
}

/**
* Replacement for setcookie
*/
function pmx_setcookie($name, $value, $expiry = 0)
{
	global $modSettings, $boardurl;

	$parts = pmx_getcookparts();
	setcookie($name, $value, $expiry, $parts['path'], $parts['host']);
}

/**
* Replacement for file_put_contents on PHP < 5.1.0
*/
function pmx_file_put_contents($fname, $data)
{
	if(@version_compare(PHP_VERSION, '5.1.0') >= 0)
		return file_put_contents($fname, $data, LOCK_EX);
	else
	{
		$fp = @fopen($fname, 'wb');
		if($fp)
		{
			@flock($fp, LOCK_EX);
			stream_set_write_buffer($fp, 0);
			$cache_bytes = fwrite($fp, $data);
			fclose($fp);
			return $cache_bytes;
		}
		else
			return -1;
	}
}

/**
* Replacement for http_build_query PHP < 5.1.3
*/
function pmx_http_build_query($data, $prefix = '', $sep = ';')
{
	$ret = array();
	foreach ((array) $data as $k => $v)
	{
		$k = urlencode($k);
		if(is_int($k) && !empty($prefix))
			$k = $prefix . $k;
		if(is_array($v) || is_object($v))
			array_push($ret, pmx_http_build_query($v, '', $sep));
		elseif(empty($v))
			array_push($ret, $k);
		else
			array_push($ret, $k .'='. urlencode($v));
	}

	if(empty($sep))
		$sep = ini_get("arg_separator.output");

	return implode($sep, $ret);
}

/**
* Replacement for parse_url PHP < 5.1.2
*/
function pmx_parse_url($data, $component = '')
{
	if(@version_compare(PHP_VERSION, '5.1.2') >= 0)
		return empty($component) ? parse_url($data) : parse_url($data, $component);
	else
	{
		$tmp = parse_url($data);
		return empty($component) ? $tmp : $tmp[$component];
	}
}
?>